package com.aitao.beans;

import com.aitao.util.Assert;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 临时文件类
 *
 * @Company QAX
 * @Author : admin
 * @Create : 2022/1/10 17:40
 */
public class TemporaryFile implements Closeable {
    // 文件路径
    private final Path path;

    // 文件状态
    private boolean isCreated;

    public TemporaryFile() {
        this.isCreated = false;
        try {
            path = Files.createTempFile(null, null);
            isCreated = true;
        } catch (IOException e) {
            isCreated = false;
            throw new RuntimeException(Assert.mark("Failed to create temporary file", new Throwable()));
        }
    }

    public OutputStream getOutputStream() throws IOException {
        return Files.newOutputStream(path);
    }

    public InputStream getInputStream() throws IOException {
        return Files.newInputStream(path);
    }

    public File getFile() {
        return path.toFile();
    }

    public long getSize() {
        try {
            return Files.size(path);
        } catch (IOException e) {
            throw new RuntimeException("Failed to get file size");
        }
    }

    @Override
    public String toString() {
        return path.toString();
    }

    @Override
    public void close() throws IOException {
        if (isCreated) {
            Files.delete(path);
        }
    }
}
